package com.we.wfc.sender.service;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.JSMSClient;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.common.model.SMSPayload;
import cn.jsms.api.schedule.model.ScheduleResult;
import cn.jsms.api.schedule.model.ScheduleSMSPayload;
import com.we.wfc.common.utils.ConverterUtil;
import com.we.wfc.sender.po.UnifiedSmsPo;
import com.we.wfc.sender.properties.SmsProp;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

/**
 * @Description: 短信相关业务
 * @Author:Liangzy(Feeling)
 * @Date:Create in 2019/10/31 7:23 下午
 */
@Slf4j
@Service
@AllArgsConstructor
@EnableConfigurationProperties({SmsProp.class})
public class SmsService {

    private final SmsProp smsProp;

    /**
     * 发送指定模板格式的任意文字短信
     *
     * @param unifiedSmsPo 短信PO
     * @return
     */
    public Boolean sendSms(UnifiedSmsPo unifiedSmsPo) {
        return send(unifiedSmsPo.getSignId(), unifiedSmsPo.getTempId(), unifiedSmsPo.getPhoneNum(), unifiedSmsPo.getParamKey(), unifiedSmsPo.getParamValue());
    }

    /**
     * 发送定时指定模板格式的任意文字短信
     *
     * @param unifiedSmsPo 短信PO
     * @return
     */
    public Boolean sendTimingSms(UnifiedSmsPo unifiedSmsPo) {
        return send(unifiedSmsPo.getSignId(), unifiedSmsPo.getTempId(), unifiedSmsPo.getPhoneNum(), unifiedSmsPo.getParamKey(), unifiedSmsPo.getParamValue(), unifiedSmsPo.getSendTime());
    }

    /**
     * 单条模板短信总控制方法
     *
     * @param signId     签名
     * @param phone      手机号
     * @param tempId     模板
     * @param paramKey   模板对应的key
     * @param paramValue 短信内容[必须是模板内的短信]
     * @return Boolean
     * @throws Exception
     */
    public Boolean send(int signId, int tempId, String phone, String paramKey, String paramValue) {

        //参数定义
        boolean res = false;
        SendSMSResult resMsg = new SendSMSResult();

        //初始化客户端
        JSMSClient client = new JSMSClient(smsProp.getMasterSecret(), smsProp.getAppkey());
        //入参 如果signId为空则代表为默认短信签名
        SMSPayload payload = SMSPayload.newBuilder()
                .setSignId(signId)
                .setTempId(tempId)
                .setMobileNumber(phone)
                .addTempPara(paramKey, paramValue)
                .build();
        try {
            //调用短信API发送
            resMsg = client.sendTemplateSMS(payload);
            log.info(resMsg.toString());
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
        }

        //返回结果不为空代表发送成功
        if (ConverterUtil.isNotEmpty(resMsg.getMessageId())) {
            res = true;
        }

        return res;
    }

    /**
     * 定时短信总控制方法
     *
     * @param signId     签名
     * @param phone      手机号
     * @param tempId     模板
     * @param paramKey   模板对应的key
     * @param paramValue 短信内容[必须是模板内的短信]
     * @param timing     时间
     * @return Boolean
     * @throws Exception
     */
    public Boolean send(int signId, int tempId, String phone, String paramKey, String paramValue, String timing) {

        //参数定义
        boolean res = false;
        ScheduleResult resMsg = new ScheduleResult();

        //初始化客户端
        JSMSClient client = new JSMSClient(smsProp.getMasterSecret(), smsProp.getAppkey());
        //入参 如果signId为空则代表为默认短信签名
        ScheduleSMSPayload payload = ScheduleSMSPayload.newBuilder()
                .setSignId(signId)
                .setTempId(tempId)
                .setMobileNumber(phone)
                .addTempPara(paramKey, paramValue)
                .setSendTime(timing)
                .build();
        try {
            ScheduleResult result = client.sendScheduleSMS(payload);
            log.info(result.toString());
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
        }

        //返回结果不为空代表发送成功
        if (ConverterUtil.isNotEmpty(resMsg.getScheduleId())) {
            res = true;
        }

        return res;
    }
}
